package spring.cloud.tasks.executor.executor.task.task_item_allot;

import com.alibaba.fastjson2.JSON;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import spring.cloud.tasks.common.task_item_allot.Executor;

@Slf4j
@Setter
@Getter
public class TaskItemAssignListener implements NodeCacheListener {
    public NodeCache nodeCache;
    public spring.cloud.tasks.executor.executor.Executor executor;
    public TaskItemAllotContentService taskItemAllotContentService;

    public TaskItemAssignListener(NodeCache nodeCache, spring.cloud.tasks.executor.executor.Executor executor) {
        this.nodeCache = nodeCache;
        this.executor = executor;
        this.taskItemAllotContentService = new TaskItemAllotContentService(this.executor.getCurator().getCuratorFramework());
    }

    @Override
    public void nodeChanged() throws Exception {
        String value = null;
        if (null != nodeCache.getCurrentData()) {
            value = new String(nodeCache.getCurrentData().getData());
        }
        log.info("value" + JSON.toJSONString(value));
        get();
    }

    public void get() throws Exception {
        Executor executor = taskItemAllotContentService.getExecutor(this.executor.getExecutorId());
        if (executor == null) {
            this.executor.getTaskMap().taskIdToTaskItemCollectionMap.clear();
        } else {
            this.executor.getTaskMap().updateLastTaskItemInfo(executor);
            //需要将this.taskIdToItemIndexListMap=和taskIdToItemIndexListMapz进行对比
            //增加和删除task 增加和删除task item
            //在这主动获取当前任务的执行频率。（前30分钟+后30分钟+如果30分钟内不存在那么至少获取到下次执行的时间频率）

        }
    }
}
